package org.apache.cordova.localfile;

import java.util.Map;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;

public class LocalFile extends CordovaPlugin {

	private CallbackContext callbackContext;

	private Activity activity;

	private JSONObject jsonObj = new JSONObject();

	@Override
	public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
		if (this.cordova.getActivity().isFinishing()) {
			return true;
		}
		this.activity = cordova.getActivity();
		setCallbackContext(callbackContext);
		if ("downloadImage".equals(action)) {
			FtpCollectionUtil ftpUtil = new FtpCollectionUtil("softwaresupport", "ssupport", "ftp.forewideaccess.com.hk", 21);
			Map<String,String> returnMap = ftpUtil.downImage(this.activity);
			try {
				jsonObj.put("returnMap", returnMap);
				callbackContext.success(jsonObj);
			} catch (JSONException e) {
				callbackContext.error(e.getMessage());
				return false;
			}
		} else if ("downloadFile".equals(action)) {
			FtpCollectionUtil ftpUtil = new FtpCollectionUtil("softwaresupport", "ssupport", "ftp.forewideaccess.com.hk", 21);
			Map<String,String> returnMap = ftpUtil.downFile(this.activity);
			try {
				jsonObj.put("returnMap", returnMap);
				callbackContext.success(jsonObj);
			} catch (JSONException e) {
				callbackContext.error(e.getMessage());
				return false;
			}
		} else {
			callbackContext.error(PluginResult.Status.INVALID_ACTION.toString());
			return false;
		}
		return true;
	}

	public CallbackContext getCallbackContext() {
		return callbackContext;
	}

	public void setCallbackContext(CallbackContext callbackContext) {
		this.callbackContext = callbackContext;
	}
}